import React, { createContext, useContext, useState, useEffect } from 'react';
import axios from 'axios';

const AUTH_API_URL = process.env.NEXT_PUBLIC_AUTH_API_URL;

interface User {
  email: string;
  // 其他用户属性...
}

interface AuthContextType {
  user: User | null;
  token: string | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  register: (email: string, password: string, verification_code: string) => Promise<void>;
  setPassword: (email: string, new_password: string, verification_code: string) => Promise<void>;
  sendVerificationCode: (email: string) => Promise<void>;
  checkDownloadPermission: () => Promise<boolean>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(null);

  useEffect(() => {
    // 在组件挂载时从 localStorage 读取用户信息和 token
    const storedUser = localStorage.getItem('user');
    const storedToken = localStorage.getItem('access_token');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }
    if (storedToken) {
      setToken(storedToken);
    }
  }, []);

  const login = async (email: string, password: string) => {
    try {
      const response = await axios.post('/auth/login', { email, password });
      const { access_token } = response.data;
      localStorage.setItem('access_token', access_token);
      localStorage.setItem('user', JSON.stringify({ email }));
      setUser({ email });
      setToken(access_token);
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        throw new Error(error.response.data.message || '登录失败，请稍后重试。');
      } else {
        throw new Error('登录失败，请稍后重试。');
      }
    }
  };

  const logout = () => {
    setUser(null);
    setToken(null);
    localStorage.removeItem('access_token');
    localStorage.removeItem('user');
  };

  const register = async (email: string, password: string, verification_code: string) => {
    try {
      const response = await axios.post('/auth/register', { email, password, verification_code });
      // 不再在这里显示 alert
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        throw new Error(error.response.data.message || '注册失败，请稍后重试。');
      } else {
        throw new Error('注册失败，请稍后重试。');
      }
    }
  };

  const setPassword = async (email: string, new_password: string, verification_code: string) => {
    try {
      const response = await axios.post('/auth/set_password', { email, new_password, verification_code });
      // 不再在这里显示 alert
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        throw new Error(error.response.data.message || '密码重置失败，请稍后重试。');
      } else {
        throw new Error('密码重置失败，请稍后重试。');
      }
    }
  };

  const sendVerificationCode = async (email: string) => {
    try {
      await axios.post('/auth/send_verification', { email });
      // 不再在这里显示 alert
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        throw new Error(error.response.data.message || '发送验证码失败，请稍后重试。');
      } else {
        throw new Error('发送验证码失败，请稍后重试。');
      }
    }
  };

  const resetPassword = async (email: string) => {
    try {
      await axios.post('/auth/reset-password', { email });
      alert('密码重置邮件已发送，请查看您的邮箱。');
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        throw new Error(error.response.data.message || '密码重置失败，请稍后重试。');
      } else {
        throw new Error('密码重置失败，请稍后重试。');
      }
    }
  };

  const checkDownloadPermission = async () => {
    try {
      const response = await axios.get('/auth/check_download_permission', {
        headers: { Authorization: `Bearer ${token}` }
      });
      return response.data.can_download;
    } catch (error) {
      if (axios.isAxiosError(error)) {
        throw error;  // 直接抛出 Axios 错误
      }
      throw new Error('检查下载权限失败');
    }
  };

  return (
    <AuthContext.Provider value={{ 
      user, 
      token, 
      login, 
      logout, 
      register, 
      setPassword, 
      sendVerificationCode,
      checkDownloadPermission 
    }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};